#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- This's login window UI - Python
# -- The users login
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2017年7月24日 12:04:32
# ----------------------------------------------------------

from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtGui import QIcon, QPalette, QColor
from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit, QGridLayout, QPushButton, QMessageBox
from files.logs import Logger
from files.threads import LoginLoadingThread
from files.threads.LoginThread import LoginThread
from files.tools import ConfigUtils


class LoginFrame(QWidget):
    _log = Logger.log();

    def __init__(self):
        self.__conf = ConfigUtils();
        # window abs path
        self.__iconPath = self.__conf.resourcesPath + self.__conf.themePath;
        # style relative path
        self.__iconRelPath = "./" + self.__conf.resources + self.__conf.themePath;
        self._log.info(self.__iconPath + " -- %s", self.__iconRelPath)
        super().__init__();
        # 初始化登陆界面
        self.loginPanel();
        # 主窗口
        from files.ui import MainWindow;
        self.__main = MainWindow();

    def loginPanel(self):
        # user name
        userNameLabel = QLabel("帐号: ");
        userNameLabel.setStyleSheet(
            "QLabel{"
            "font-family: Arial;"
            "font-weight: bold;"
            "font-size: 15px;"
            "color: #104E8B;}");
        self.__userNameLineEdit = QLineEdit();
        self.__userNameLineEdit.setPlaceholderText("请输入您的帐号");
        # TODO
        self.__userNameLineEdit.setText("15072330003");
        self.__userNameLineEdit.setStyleSheet(
            "QLineEdit{"
            "background-color: #F0FFF0;"
            "font-family: Arial;"
            "font-size: 15px;"
            "color: #104E8B;"
            "border: 0;"
            "border-bottom: 1 solid #00BFFF;"
            "border-radius: 8px;"
            "width: 230px;"
            "height: 28px;}"
            "QLineEdit:focus{"
            "background-color: #F0FFF0;"
            "font-family: Arial;"
            "font-size: 15px;"
            "color: #104E8B;"
            "border: 0;"
            "border-top: 1 solid #000080;"
            "border-bottom: 1 solid #000080;"
            "border-radius: 8px;"
            "width: 230px;"
            "height: 28px;}");
        # password
        passwordLabel = QLabel("密码: ");
        passwordLabel.setStyleSheet(
            "QLabel{"
            "font-family: Arial;"
            "font-weight: bold;"
            "font-size: 15px;"
            "color: #104E8B;}");
        self.__passwordLineEdit = QLineEdit();
        self.__passwordLineEdit.setPlaceholderText("请输入您的密码");
        # TODO
        self.__passwordLineEdit.setText("admin");
        # 设置模式
        self.__passwordLineEdit.setEchoMode(QLineEdit.Password);
        self.__passwordLineEdit.setStyleSheet(
            "QLineEdit{"
            "background-color: #F0FFF0;"
            "font-family: Arial;"
            "font-size: 15px;"
            "color: #104E8B;"
            "border: 0;"
            "border-bottom: 1 solid #00BFFF;"
            "border-radius: 8px;"
            "width: 230px;"
            "height: 28px;}"
            "QLineEdit:focus{"
            "background-color: #F0FFF0;"
            "font-family: Arial;"
            "font-size: 15px;"
            "color: #104E8B;"
            "border: 0;"
            "border-top: 1 solid #000080;"
            "border-bottom: 1 solid #000080;"
            "border-radius: 8px;"
            "width: 230px;"
            "height: 28px;}");

        self.__loginButton = QPushButton(QIcon(self.__iconPath + "/ok.png"), "登 陆");
        self.__loginButton.setFixedSize(143, 40);
        self.__loginButton.setStyleSheet(
            "QPushButton{"
            "color: #fff;"
            "font-size: 18px;"
            "font-family: Arial;"
            "border-style: outset;"
            "background-image: url(" + self.__iconRelPath + "/button_01.png);"
                                                            "background-repeat: repeat-xy;"
                                                            "background-position: Center;"
                                                            "background-attachment: fixed;"
                                                            "background-clip: padding;}"
                                                            "QPushButton:hover{"
                                                            "border-style: inset;"
                                                            "background-image: url(" + self.__iconRelPath + "/button_02.png);"
                                                                                                            "background-repeat: repeat-xy;"
                                                                                                            "background-position: Center;"
                                                                                                            "background-attachment: fixed;"
                                                                                                            "background-clip: padding;}");
        # button 提示信息
        self.__loginButton.setToolTip("客户端登陆");
        self.__loginButton.clicked.connect(self.onSubmit);

        self.__resetButton = QPushButton(QIcon(self.__iconPath + "/reset.png"), "重 置");
        self.__resetButton.setFixedSize(143, 40);
        self.__resetButton.setStyleSheet(
            "QPushButton{"
            "color: #fff;"
            "font-size: 18px;"
            "font-family: 微软雅黑;"
            "border-style: outset;"
            "background-image: url(" + self.__iconRelPath + "/button_01.png);"
                                                            "background-repeat: repeat-xy;"
                                                            "background-position: Center;"
                                                            "background-attachment: fixed;"
                                                            "background-clip: padding;}"
                                                            "QPushButton:hover{"
                                                            "border-style: inset;"
                                                            "background-image: url(" + self.__iconRelPath + "/button_02.png);"
                                                                                                            "background-repeat: repeat-xy;"
                                                                                                            "background-position: Center;"
                                                                                                            "background-attachment: fixed;"
                                                                                                            "background-clip: padding;}");
        # button 提示信息
        self.__resetButton.setToolTip("信息重置");
        self.__resetButton.clicked.connect(self.onReset);

        # 登陆加载标签
        self.__loadLabel = QLabel("登陆中...");
        self.__loadLabel.setFixedSize(143, 40);
        self.__loadLabel.setAlignment(Qt.AlignCenter);
        self.__loadLabel.setStyleSheet(
            "QLabel{"
            "color: #fff;"
            "font-size: 18px;"
            "font-family: 微软雅黑;"
            "border-style: outset;"
            "background-image: url(" + self.__iconRelPath + "/button_01.png);"
                                                            "background-repeat: repeat-xy;"
                                                            "background-position: Center;"
                                                            "background-attachment: fixed;"
                                                            "background-clip: padding;}");
        self.__loadLabel.hide();

        # 网格布局
        mainLayout = QGridLayout(self);
        mainLayout.addWidget(userNameLabel, 0, 0, 1, 1);
        mainLayout.addWidget(self.__userNameLineEdit, 0, 1, 1, 3);
        mainLayout.addWidget(passwordLabel, 1, 0, 1, 1);
        mainLayout.addWidget(self.__passwordLineEdit, 1, 1, 1, 3);
        mainLayout.addWidget(self.__loginButton, 2, 0, 1, 2);
        mainLayout.addWidget(self.__resetButton, 2, 2, 1, 2);
        mainLayout.addWidget(self.__loadLabel, 2, 1, 1, 2);
        # 设置间距
        mainLayout.setSpacing(20);

        qPalette = QPalette();
        qPalette.setColor(QPalette.Background, QColor(213, 232, 251));
        # 设置布局
        self.setLayout(mainLayout);
        # 设置边距
        self.setContentsMargins(10, 10, 10, 10);
        # 设置背景色
        self.setAutoFillBackground(True);
        self.setPalette(qPalette);
        self.setWindowIcon(QIcon(self.__iconPath + "/favicon.png"));
        self.setFixedSize(350, 280);
        self.setWindowTitle("发票数据客户端 - 登录");
        self.show();

    # 用户登陆
    @pyqtSlot()
    def onSubmit(self):
        userName = self.__userNameLineEdit.text().strip();
        password = self.__passwordLineEdit.text().strip();
        self._log.info("user login info: {} - {}".format(userName, password));
        self.__messageBox = QMessageBox(self);
        self.__messageBox.setWindowTitle("提示信息");
        if userName.__len__() == 0:
            self._log.warn("帐号不允许为空, 请输入帐号！");
            # QMessageBox.question(self, '提示信息', "帐号不允许为空, 请输入帐号！", QMessageBox.Ok);
            self.__messageBox.setText("帐号不允许为空, 请输入帐号！");
            self.__messageBox.show();
        elif password.__len__() == 0:
            self._log.warn("密码不允许为空, 请输入密码！");
            # QMessageBox.question(self, '提示信息', "密码不允许为空, 请输入密码！", QMessageBox.Ok);
            self.__messageBox.setText("密码不允许为空, 请输入密码！");
            self.__messageBox.show();
        else:
            self._log.info("校验用户信息 ...");
            # 创建线程 - 登录
            self.loginTd = LoginThread();
            self.loginTd.userName = userName;
            self.loginTd.password = password;
            # 注册信号处理函数
            self.loginTd._signal.connect(self.loginVerify);
            # 启动线程
            # self.loginTd.start();
            # 禁用输入框
            self.__userNameLineEdit.setEnabled(False);
            self.__passwordLineEdit.setEnabled(False);
            self.__loginButton.hide();
            self.__resetButton.hide();
            # 创建线程 - 加载
            self.loadingTd = LoginLoadingThread();
            # 注册信号处理函数
            self.loadingTd._signal.connect(self.loginLoading);
            # 启动线程
            self.loginTd.start();
            self.loadingTd.start();
            self.__loadLabel.show();

    # 信息重置
    @pyqtSlot()
    def onReset(self):
        self._log.info("data reset ...");
        self.__userNameLineEdit.setText("");
        self.__passwordLineEdit.setText("");

    # 登陆校验
    def loginVerify(self, loginRequest):
        statusCode = loginRequest.code;
        self._log.info("statusCode : %s", statusCode);
        if 200 == statusCode:
            result = loginRequest.t;
            self._log.info("login result : %s", result);
            if None is not result and 200 == result["code"]:
                self._log.info("登录成功：%s", result);
                # 隐藏当前窗口
                self.hide();
                # 显示主窗口
                self.__main.timer.start(100, self.__main);
                self.__main.initQMainWindow();
            else:
                errMsg = result["msg"];
                self._log.error("用户登录失败: %s", errMsg);
                self.__messageBox.setText(errMsg);
                self.__messageBox.show();
                self.showModule();
        elif 408 == statusCode:
            self._log.error("请求异常 - 用户登录失败！");
            self.__messageBox.setText(loginRequest.msg);
            self.__messageBox.show();
            self.showModule();
        elif 503 == statusCode:
            self._log.error("请求异常 - 用户登录失败！");
            self.__messageBox.setText(loginRequest.msg);
            self.__messageBox.show();
            self.showModule();
        else:
            self._log.error("请求异常 - 用户登录失败！");
            self.__messageBox.setText("登录请求异常...");
            self.__messageBox.show();
            self.showModule();
        # 停止线程
        self.loadingTd.terminate();
        self.loginTd.terminate();

    # 登陆加载...
    def loginLoading(self, msg):
        self._log.warn("登陆 - 加载中 ...");
        s = "登陆中";
        self.__loadLabel.setText(s + msg);

    # 异常回滚组件状态
    def showModule(self):
        self.__userNameLineEdit.setEnabled(True);
        self.__passwordLineEdit.setEnabled(True);
        self.__loadLabel.hide();
        self.__loginButton.show();
        self.__resetButton.show();
        self._log.warn("登陆 - 异常回滚组件状态 ...");
